package com.xxx.yuedong.mall.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.github.pagehelper.PageInfo;
import com.xxx.yuedong.common.R;
import com.xxx.yuedong.mall.common.Constant;
import com.xxx.yuedong.mall.controller.form.CreateOrderForm;
import com.xxx.yuedong.mall.controller.form.DirCreateOrderForm;
import com.xxx.yuedong.mall.exception.MallException;
import com.xxx.yuedong.mall.exception.MallExceptionEnum;
import com.xxx.yuedong.mall.model.dao.OrderMapper;
import com.xxx.yuedong.mall.model.pojo.Order;
import com.xxx.yuedong.mall.model.vo.OrderVO;
import com.xxx.yuedong.mall.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 描述：     订单Controller
 * @author hc
 */
@RestController
@Api(tags = "前台订单相关接口")
@Slf4j
public class OrderController {

    @Resource
    OrderService orderService;

    @Autowired
    OrderMapper orderMapper;

    @Value("${alipay.publicKey}")
    private String publicKey;

    @PostMapping("order/create")
    @ApiOperation(value = "创建订单")
    public R create(@RequestBody @Valid CreateOrderForm form) {
        String code = orderService.create(form);
        return R.ok().put("code",code);
    }

    @PostMapping("order/directCreateOrder")
    @ApiOperation(value = "直接购买创建订单")
    public R directCreateOrder(@RequestBody @Valid DirCreateOrderForm form) {
        String code = orderService.directCreateOrder(form);
        return R.ok().put("code",code);
    }

    @GetMapping("order/detail")
    @ApiOperation(value = "前台订单详情")
    public R detail(@RequestParam String orderNo) {
        OrderVO orderVO = orderService.detail(orderNo);
        return R.ok().put("order",orderVO);
    }

    @GetMapping("order/list")
    @ApiOperation(value = "前台订单列表")
    public R list(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        PageInfo pageInfo = orderService.listForCustomer(pageNum, pageSize);
        return R.ok().put("page",pageInfo);
    }

    /**
     * 订单取消
     */
    @PostMapping("order/cancel")
    @ApiOperation(value = "前台取消订单")
    public R cancel(@RequestParam String orderNo) {
        orderService.cancel(orderNo);
        return R.ok();
    }

    @PostMapping("order/recieveMessage")
    @ApiOperation(value = "接收支付回调消息")
    public void recieveMessage(HttpServletResponse response, HttpServletRequest request) throws Exception {
        request.setCharacterEncoding("utf-8");
        System.out.println("接收到响应");
        //获取支付宝POST过来反馈信息，将异步通知中收到的待验证所有参数都存放到map中
        Map<String,String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0;i < values.length;i++){
                valueStr =  (i==values.length-1)?valueStr + values [i]:valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put (name,valueStr);
        }
        //调用SDK验证签名
        //公钥验签示例代码
        System.out.println(params);
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(params,publicKey,"UTF-8","RSA2");
            if (signVerified){
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus)){
                    String outTradeNo = params.get("out_trade_no");
                    Order order = orderMapper.selectByOrderNo(outTradeNo);
                    //查不到订单，报错
                    if (order == null) {
                        throw new MallException(MallExceptionEnum.NO_ORDER);
                    }
                    if (order.getOrderStatus() == Constant.OrderStatusEnum.NOT_PAID.getCode()) {
                        order.setOrderStatus(Constant.OrderStatusEnum.PAID.getCode());
                        order.setPayTime(new Date());
                        orderMapper.updateByPrimaryKeySelective(order);
                    } else {
                        throw new MallException(MallExceptionEnum.WRONG_ORDER_STATUS);
                    }

                    //根据罚款单ID查询用户ID
//                  int userId = orderService.s(outTradeNo);
                    //向用户推送结果
//                  WebSocketService.sendInfo("付款成功",userId + "");

                } else{
                    log.error("订单支付失败");
                }
            } else {
                log.error("数字签名异常");
                response.sendError(500,"数字签名异常");
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成支付二维码
     */
//    @GetMapping("order/qrcode")
//    @ApiOperation(value = "生成支付二维码")
//    public R qrcode(@RequestParam String orderNo) {
//        String pngAddress = orderService.qrcode(orderNo);
//        return R.ok(pngAddress);
//    }

//    @GetMapping("pay")
//    @ApiOperation(value = "支付接口")
//    public R pay(@RequestParam String orderNo) {
//        orderService.pay(orderNo);
//        return R.ok();
//    }
}
